package JSF;

import Entidades.Estado;
import Entidades.Expediente;
import Entidades.Inmuebles;
import Entidades.InteresArea;
import Entidades.InteresAreaPK;
import Entidades.Interesado;
import Entidades.TipoDocTra;
import Entidades.Trabajador;
import JSF.util.JsfUtil;
import JSF.util.PaginationHelper;
import SessionB.ExpedienteFacade;
import SessionB.InteresAreaFacade;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import java.io.Serializable;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.save.JRPdfSaveContributor.*;
import net.sf.jasperreports.view.JRViewer.*;
import net.sf.jasperreports.view.save.JRMultipleSheetsXlsSaveContributor.*;
import org.apache.commons.io.IOUtils;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;

//import org.primefaces.model.DefaultStreamedContent;
//import org.primefaces.model.StreamedContent;
@Named("expedienteController")
@SessionScoped
public class ExpedienteController implements Serializable {

    private Expediente current;
    private TipoDocTra tipotradoc;
    private InteresArea interarea;
    private Interesado interesado;
    private Inmuebles inmueble;
    private Trabajador trabajador;
    private DataModel items = null;
    private String cadena_conexion = "jdbc:mysql://localhost:3306/emilima_tradoc";
    private String password = "carloscd3";
    private static Connection conn = null;
    private JasperPrint jasperPrint;
    @EJB
    private SessionB.ExpedienteFacade ejbFacade;
//    private SessionB.UsuarioFacade ejbFacade;
    @EJB
    private SessionB.InteresAreaFacade ejbAint;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private Date fecha_emision;
    private Date fecha_ini;
    private Date fecha_fin;
    private String tipoPriori;
    private String tipoDocAdj;
    private String estado;
    private Expediente expedient;
    private List<Expediente> lista;
    private List<Expediente> list_exped;
    private List<Expediente> filteredExped;
    private JasperPrint fill1;
    @ManagedProperty("#{usuarioController}")
    private ExpedienteController usuarioresp;

    public ExpedienteController getUsuarioresp() {
        return usuarioresp;
    }

    public void setUsuarioresp(ExpedienteController usuarioresp) {
        this.usuarioresp = usuarioresp;
    }

    public ExpedienteController() {
        expedient = new Expediente();
        //venta.setDetalleVentaProductoList(new LinkedList<DetalleVentaProducto>());
        //detalle_venta_Producto = new DetalleVentaProducto();
        lista = new LinkedList<Expediente>();
        list_exped = new ArrayList<Expediente>();
    }

    public Expediente getSelected() {
        if (current == null) {
            current = new Expediente();
            selectedItemIndex = -1;
        }
        return current;
    }

    public void onRowSelect(SelectEvent event) {
        FacesMessage msg = new FacesMessage("Exped Selected", ((Expediente) event.getObject()).getCodExp());

        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public Trabajador getTrabajador() {
        return trabajador;
    }

    public void setTrabajador(Trabajador trabajador) {
        this.trabajador = trabajador;
    }

    public InteresAreaFacade getEjbAint() {
        return ejbAint;
    }

    private ExpedienteFacade getFacade() {
        return ejbFacade;
    }

    public String getTipoPriori() {
        return tipoPriori;
    }

    public void setTipoPriori(String tipoPriori) {
        this.tipoPriori = tipoPriori;
    }

    public String getTipoDocAdj() {
        return tipoDocAdj;
    }

    public void setTipoDocAdj(String tipoDocAdj) {
        this.tipoDocAdj = tipoDocAdj;
    }

    //********************************************************************
    public void initQueryReport() throws JRException {
        try {
            System.out.println(" Inicio PDF");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            Date fechaIni = fecha_ini; //expedient.getCodExp().toString();
            Date fechaFin = fecha_fin;
            String tpriori = expedient.getTipoPriorida().getIdPriori();
            System.out.println(" FIni : " + fecha_ini);
            System.out.println(" FFin : " + fecha_fin);
            System.out.println(" Priori : " + tpriori);
            Map parameters = new HashMap();
            parameters.put("P_FIni", fechaIni);
            parameters.put("P_FFin", fechaFin);
            parameters.put("P_Priori", tpriori);
            fill1 = JasperFillManager.fillReport("C:\\eltramited\\cede3-war\\web\\reports\\SegReg_Priori_Fecha.jasper", parameters, conn);
        } catch (Exception e) {
            System.out.println();
        }
    }
    ServletResponse respnce;
    HttpServletResponse respons;

    public void initverweb() throws JRException {
        try {
            String template = "SegRegPriori.jasper";
            initQueryReport();
            respnce = (ServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            respons = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            respons.setContentType("application/pdf");
            String filen = "Segregpriori";
            respons.setHeader("Content-Disposition", "inline ; filename=\"" + filen + "\"");
            respons.setContentType("application/pdf");
            ServletOutputStream out = respnce.getOutputStream();
            JRPdfExporter pdf = new JRPdfExporter();
            pdf.setParameter(JRExporterParameter.JASPER_PRINT, fill1);
            pdf.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
            pdf.exportReport();
        } catch (Exception e) {
        }
    }

//------------------------------  Reporta Reg x Prioridad  ---------------------    
    public void seg_PrioriPrn(ActionEvent actionEvent) throws JRException, IOException {
        initPriori();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "MovPriorida";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    public void initPriori() throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            Date fechaIni = fecha_ini; //expedient.getCodExp().toString();
            Date fechaFin = fecha_fin;
            String tpriori = expedient.getTipoPriorida().getIdPriori();
            Map parameters = new HashMap();
            parameters.put("P_FIni", fechaIni);
            parameters.put("P_FFin", fechaFin);
            parameters.put("P_Priori", tpriori);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/SegReg_Priori_Fecha.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }

//------------------------------  Reporta Reg x Tipo Tramite  -----------------    
    public void seg_TipTramite(ActionEvent actionEvent) throws JRException, IOException {
        initTTramite();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "MovTTramit";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    public void initTTramite() throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            Date fechaIni = fecha_ini; //expedient.getCodExp().toString();
            Date fechaFin = fecha_fin;
            String tpriori = expedient.getTipoTramite().getIdTipoTramite();
            Map parameters = new HashMap();
            parameters.put("P_FIni", fechaIni);
            parameters.put("P_FFin", fechaFin);
            parameters.put("P_ttramite", tpriori);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/SegReg_TTramite.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }
    //------------------------------  Reporta Reg x Area Interesada  -----------------    

    public void seg_AreaInt(ActionEvent actionEvent) throws JRException, IOException {
        initAreaInt();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "MovAreaInt";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    public void initAreaInt() throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            Date fechaIni = fecha_ini; //expedient.getCodExp().toString();
            Date fechaFin = fecha_fin;
            String tInteres = expedient.getInteresArea().getInteresAreaPK().getIdInter();
            String tAreaInt = expedient.getInteresArea().getInteresAreaPK().getIdIntArea();
            Map parameters = new HashMap();
            parameters.put("P_FIni", fechaIni);
            parameters.put("P_FFin", fechaFin);
            parameters.put("P_tInteres", tInteres);
            parameters.put("P_tAreaInt", tAreaInt);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/SegReg_AreaInt.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }
    //------------------------------  Reporta Reg x Area Interesada  -----------------    

    public void seg_EstaDoc(ActionEvent actionEvent) throws JRException, IOException {
        initStad();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "MovAreaInt";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    public void initStad() throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            Date fechaIni = fecha_ini; //expedient.getCodExp().toString();
            Date fechaFin = fecha_fin;
            String tInteres = expedient.getInteresArea().getInteresAreaPK().getIdInter();
            String tAreaInt = expedient.getInteresArea().getInteresAreaPK().getIdIntArea();
            Map parameters = new HashMap();
            parameters.put("P_FIni", fechaIni);
            parameters.put("P_FFin", fechaFin);
            parameters.put("P_tInteres", tInteres);
            parameters.put("P_tAreaInt", tAreaInt);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/SegReg_Estado.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }
//---------------------------------------------------------  
//---------------------------------------------------------    

    public void repweb() {

        try {

            System.out.println(" Inicio repweb");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);

            System.out.println("... pdf...");
            FacesContext fc = FacesContext.getCurrentInstance();
            ExternalContext ec = fc.getExternalContext();
            String tplPath = ec.getRealPath("/reports/Regist_Cargo.jrxml"); // .jrxml
            JasperReport jasperReport = JasperCompileManager.compileReport(tplPath);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
            String pdfName = "/cede3.pdf";
            String pdfPath = ec.getRealPath(pdfName);
            JasperExportManager.exportReportToPdfFile(jasperPrint, pdfPath);
            System.out.println("PDF ready!");
            ec.responseReset();
            ec.setResponseContentType(ec.getMimeType(pdfPath)); //ec.setResponseContentLength(contentLength); 
            System.out.println(" 10 ");
//            ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + pdfName + "\"");
            String fileNa = "Reg_Cargo";
            ec.setResponseHeader("Content-Disposition", "inline; filename=\"" + fileNa + "\"");
//            respons.setHeader("Content-Disposition", "inline");
            System.out.println(" 11 ");
            InputStream input = new FileInputStream(pdfPath);
            System.out.println(" 12 ");
            OutputStream output = ec.getResponseOutputStream();
            System.out.println(" 13 ");
// hay varias librerias
            IOUtils.copy(input, output);
            System.out.println(" 14 ");
            System.out.println("Sending to browser...");
            System.out.println(" 15 ");
            fc.responseComplete();



            System.out.println(" 16 ");

        } catch (Exception e) {
        }




    }

//3    
    public void inicia() throws JRException {
        try {
            System.out.println(" mejor ");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            //     String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Regist_Cargo.jasper");
            JasperPrint jasperPrint = JasperFillManager.fillReport("C:\\eltramited\\cede3-war\\web\\reports\\Regist_Cargo.jasper", parameters, conn);

        } catch (Exception e) {
        }
    }

    public void mejor() throws IOException, JRException {
        //  public void mejor(ActionEvent actionEvent) throws IOException, JRException {
//    public String mejor(Expediente exped) throws IOException, JRException {
        //  inicia();
        try {
            System.out.println(" mejor ");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            System.out.println("1");
            conn.setAutoCommit(false);
            System.out.println("2");
            String idCliente = expedient.getCodExp().toString();
//            String idCliente = exped.getCodExp();

//                  String idCliente = "10";
            System.out.println("3 : " + idCliente);
            Map parameters = new HashMap();
            System.out.println("4");
            parameters.put("P_IdReg", idCliente);
            System.out.println("5");
            //     String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Regist_Cargo.jasper");
            JasperPrint jasperPrint1 = JasperFillManager.fillReport("C:\\eltramited\\cede3-war\\web\\reports\\Regist_Cargo.jasper", parameters, conn);
            System.out.println("6");
            HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            System.out.println("7");
            //          ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            ServletOutputStream servletOutputStream = null;
            System.out.println("8");
            JasperExportManager.exportReportToPdfStream(jasperPrint1, servletOutputStream);
            System.out.println("9");
        } catch (Exception e) {
        }
//        return null;
    }

    public void initov() throws JRException {
        try {
            System.out.println(" Inicio PDF");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            //    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(listOfUser);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Regist_Cargo.jasper");
            //   jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), beanCollectionDataSource);
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }

    public void PDFov(ActionEvent actionEvent) throws JRException, IOException {
        initov();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        //     httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
        String fileNa = "Reg_Cargo";
//            ec.setResponseHeader("Content-Disposition", "inline; filename=\"" + fileNa + "\"");
//        httpServletResponse.addHeader("Content-disposition", "inline");
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        //             httpServletResponse.addHeader("Content-disposition : inline" , "filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

// ------------------ Cantidad de Registros recibidos Acumulado x Tipo Tramite
    public void cantReg(ActionEvent actionEvent) throws JRException, IOException {
        iniCant();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "Reg_NRegrecib";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    public void iniCant() throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            Map parameters = new HashMap();
            //    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(listOfUser);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Registr_NRegRecib.jasper");
            //   jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), beanCollectionDataSource);
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);

        } catch (Exception e) {
        }

    }
// ------------------ Cantidad de Registros recibidos Acumulado x Tipo Tramite

    public void cantDiaria(ActionEvent actionEvent) throws JRException, IOException {
        iniCantDia();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        //     httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");


        String fileNa = "Reg_DetRegDiario";
//            ec.setResponseHeader("Content-Disposition", "inline; filename=\"" + fileNa + "\"");

//        httpServletResponse.addHeader("Content-disposition", "inline");
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        //             httpServletResponse.addHeader("Content-disposition : inline" , "filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    public void iniCantDia() throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            Map parameters = new HashMap();
            //    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(listOfUser);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Registr_Mensual.jasper");
            //   jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), beanCollectionDataSource);
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);

        } catch (Exception e) {
        }

    }

    //*************** Doc Adjuntos PDF
    public void initov2() throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/DocAdjuntos.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }

    public void docAjuntPrn(ActionEvent actionEvent) throws JRException, IOException {
        initov2();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "DocAdjuntos";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }
//********** Movim Derivaciones del Exped

    public void reg_DerivaPrn2(ActionEvent actionEvent) throws JRException, IOException {
        initMov2();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "MoviDerivac";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    public void initMov2() throws JRException {
        try {
            System.out.println(" Inicio PDF");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Registr_Movim2.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }
    //**************  ******************************

//------------------------------------------------------------------    
    public void init() throws JRException {
        try {
            System.out.println(" Inicio PDF 162");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            System.out.println(" a ");
//            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Regist_Cargo.jasper");
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Regist_Cargo.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
            System.out.println(" b ");
//----------------------------------------------            
            HttpServletResponse response = null;
            System.out.println(" b1 ");
            ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
            System.out.println(" b2 ");
            response = (HttpServletResponse) ectx.getResponse();
            System.out.println(" b3 ");
//            String dirInformes = "reportes";//nombre de la carpeta donde tienes el informe
//            String reporteNombre = "reporte1"; //  nombre del reporte a ejecutar

//            String reporteJasper = /*"reportes\\" +*/ dirInformes + "\\" + reporteNombre;
//            reporteJasper = request.getSession().getServletContext().getRealPath(reporteJasper);
            OutputStream oS = null;
            System.out.println(" b4 ");
//            oS = response.getOutputStream();
            System.out.println(" b5 ");
// Compilamos el .jrxml y lo cargamos : reporteJasper
            final String jasperName = JasperCompileManager.compileReportToFile(reportPath);
            final JasperReport report = (JasperReport) JRLoader.loadObject(jasperName);


// Rellenamos el report pasándole al informe la lista de parámetros y el datasource 

            // path
//            System.out.println(" 15 jasperTemplate : " + jasperTemplate);
            JasperReport jasperReport1 = JasperCompileManager.compileReport(reportPath);

            final JasperPrint print = JasperFillManager.fillReport(report, parameters, conn);
// Exportamos el informe a HTML 
            System.out.println(" c ");
            final JRHtmlExporter exporter = new JRHtmlExporter();
            System.out.println(" d ");
//            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);  
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  //  
            System.out.println(" e ");
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, oS);
            System.out.println(" f ");
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "image?image=");
            System.out.println(" g ");
            exporter.exportReport();
            System.out.println(" saliendo image ----");







        } catch (Exception e) {
        }
    }

    public void PDF() throws JRException, IOException {
//        System.out.println(" ----  Ingresa a Init");
        init();
        /*
         //        System.out.println(" ----  Sale de Init");
         HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
         //        System.out.println(" ----  Pdf 1"); // httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
         httpServletResponse.addHeader("Content-disposition", "attachment; filename=reg_cargo.pdf");
         //        System.out.println(" ----  Pdf 2");
         ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
         //        System.out.println(" ----  Pdf 3");
         JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
         //        System.out.println(" ----  Pdf 4");
         FacesContext.getCurrentInstance().responseComplete();
         //        System.out.println(" ----  Pdf 5");

         // pruebas --------------------------------------------

         */

    }

    public void pdf1() throws JRException, IOException, SQLException {

        /*
         try {
         System.out.println(" Inicio PDF");
         conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
         conn.setAutoCommit(false);
         
         String idCliente = expedient.getCodExp().toString();
         Map parameters = new HashMap();
         parameters.put("P_IdReg", idCliente);
            
         String report = "C:/eltramited/cede3-war/web/reports/Regist_Cargo.jasper";

         String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Regist_Cargo.jasper");
         JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
         HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
         httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
         ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
         JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
         FacesContext.getCurrentInstance().responseComplete();
         System.out.println(" fin PDF");
         } catch (Exception e) {
         System.out.println("  error "+e);
         }
         */
    }

    public void print() {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            //  Map<String, String> parameters = new HashMap<String, String>();
            String idCliente = expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);

            String report = "C:/eltramited/cede3-war/web/reports/Regist_Cargo.jasper";
            //      JasperPrint print = JasperFillManager.fillReport(report, parameters, conn);

            //       JasperFillManager.fillReportToFile("C:/Reports/myreport.jasper", parameters, conn);
            JasperFillManager.fillReportToFile("C:/eltramited/cede3-war/web/reports/Regist_Cargo.jasper", parameters, conn);
            JasperExportManager.exportReportToPdfFile("C:/eltramited/cede3-war/web/reports/Regist_Cargo.jrxml");
        } catch (JRException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            /*
             * Cleanup antes de salir 
             */
            try {
                if (conn != null) {
                    conn.rollback();
                    System.out.println("ROLLBACK EJECUTADO");
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void pdfweb() {
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found.");
            //  System.exit(1);
        }
        //inicializaLogger();
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            System.out.println(" --------------- Conecto : " + conn);
        } catch (SQLException e) {
            System.out.println("Error de conexión: " + e.getMessage());
            System.exit(4);
        }
        try {
            //   Map parameters = new HashMap();
            String idCliente = expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);

            System.out.println(" 1 : ");
            JasperReport report = JasperCompileManager.compileReport(extContext.getRealPath("/reports/Regist_Cargo.jrxml"));
            System.out.println(" 2 : " + report);
            JasperPrint print = JasperFillManager.fillReport(report, parameters, conn);
            System.out.println(" 3 : " + print);
            // Exporta el informe a PDF
            JasperExportManager.exportReportToPdfFile(print, extContext.getRealPath("/reports/Regist_Cargo.pdf"));
            System.out.println(" 4 : ");
            //Para visualizar el pdf directamente desde java

            JasperViewer.viewReport(print, false);

            System.out.println(" 5 : ");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            /*
             * Cleanup antes de salir 
             */
            try {
                if (conn != null) {
                    conn.rollback();
                    System.out.println("ROLLBACK EJECUTADO");
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //****************
    //import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperRunManager; 
    //  public class JasperReportsBrowserDemoServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //        File reportFile = new File(getServletConfig().getServletContext().getRealPath("/reports/Simple_Report.jasper"));
        String path = "reports/Registr_Cargo.jrxml";
        InputStream jasperTemplate = FacesContext.getCurrentInstance()
                .getExternalContext().getResourceAsStream(path);
        InputStream reportFile = jasperTemplate;
        byte[] bytes = null;
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            //     bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), new HashMap(), new JREmptyDataSource());
            String idCliente = expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            bytes = JasperRunManager.runReportToPdf(jasperTemplate, parameters, conn);
            response.setContentType("application/pdf");
            response.setContentLength(bytes.length);
            servletOutputStream.write(bytes, 0, bytes.length);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (JRException e) { // display stack trace in the browser 
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            e.printStackTrace(printWriter);
            response.setContentType("text/plain");
            response.getOutputStream().print(stringWriter.toString());
        }
    }

//****************
    public void printReport31() throws JRException, IOException, SQLException {
        System.out.println("****************** prinReport31 ********************");
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found.");
            System.exit(1);
        }
        //Para iniciar el Logger.
        //inicializaLogger();
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            System.out.println(" --------------- Conecto : " + conn);
        } catch (SQLException e) {
            System.out.println("Error de conexion: " + e.getMessage());
            System.exit(4);
        }
        //   String path = "reports/Regist_Cargo.jrxml";
        //   InputStream jasperTemplate = FacesContext.getCurrentInstance()
        //           .getExternalContext().getResourceAsStream(path);
        //    System.out.println(" ... jasperTemplate ..." + jasperTemplate);
        //    JasperReport jasperReport = JasperCompileManager.compileReport(jasperTemplate);
        String idCliente = expedient.getCodExp().toString();
        Map parameters = new HashMap();
        parameters.put("P_IdReg", idCliente);

        //       JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
/*
         HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();

         response.setContentType("application/pdf");
         response.setHeader("Content-Disposition", "attachment; filename=\"rec_cargo.pdf\"");
         try (ServletOutputStream outputStream = response.getOutputStream()) {
         JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
         outputStream.flush();
         JasperViewer.viewReport(jasperPrint, false);
         }
         FacesContext.getCurrentInstance().renderResponse();
         FacesContext.getCurrentInstance().responseComplete();
         //   JasperViewer.viewReport(jasperPrint,false);
         */

        String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Regist_Cargo.jasper");
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();


    }

    public void printReport3() throws JRException, IOException {
        try {
            System.out.println("   printReport3() ...");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            System.out.println(" 12 ");
            conn.setAutoCommit(false);
            System.out.println(" 13 ");
            String path = "/reports/Regist_Cargo.jrxml";
            System.out.println(" 14 ");
            InputStream jasperTemplate = FacesContext.getCurrentInstance()
                    .getExternalContext().getResourceAsStream(path);
            // path
            System.out.println(" 15 jasperTemplate : " + jasperTemplate);
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperTemplate);
            System.out.println(" 16 ");
//            Map parameters = new HashMap();

            String idCliente = expedient.getCodExp().toString();
            System.out.println(" 17 ");
            Map parameters = new HashMap();
            System.out.println(" 18 ");
            parameters.put("P_IdReg", idCliente);
            System.out.println(" 2 ");

            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
            System.out.println(" 3 ");
            HttpServletResponse response = (HttpServletResponse) FacesContext
                    .getCurrentInstance().getExternalContext().getResponse();
            System.out.println(" 5 ");
            response.setContentType("application/pdf");
            System.out.println(" 6 ");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"report.pdf\"");
            System.out.println(" 7 ");
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);

                outputStream.flush();
                System.out.println(" 8 ");
            }
            System.out.println(" 9 ");
            FacesContext.getCurrentInstance().renderResponse();
            FacesContext.getCurrentInstance().responseComplete();
            System.out.println(" saliendo printReport3() ...");
            JasperViewer.viewReport(jasperPrint, false);
        } catch (Exception e) {
        }
    }

//*----------------------------------------------------------------------        
    public void printReport3web() throws JRException, IOException {
        try {
            System.out.println("   printReport3web() ...");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            System.out.println(" 12 ");
            conn.setAutoCommit(false);
            System.out.println(" 13 ");
            String path = "/reports/Regist_Cargo.jrxml";
            System.out.println(" 14 ");
            InputStream jasperTemplate = FacesContext.getCurrentInstance()
                    .getExternalContext().getResourceAsStream(path);
            // path
            System.out.println(" 15 jasperTemplate : " + jasperTemplate);
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperTemplate);
            System.out.println(" 16 ");
//            Map parameters = new HashMap();

            String idCliente = expedient.getCodExp().toString();
            System.out.println(" 17 ");
            Map parameters = new HashMap();
            System.out.println(" 18 ");
            parameters.put("P_IdReg", idCliente);
            System.out.println(" 2 ");

//                Mostrarlo en el navegador

            //       HttpServletResponse response = null;
//            String dirInformes = "reportes";//nombre de la carpeta donde tienes el informe
//            String reporteNombre = "reporte1"; //  nombre del reporte a ejecutar

//            String reporteJasper = /*"reportes\\" +*/ dirInformes + "\\" + reporteNombre;
//            reporteJasper = request.getSession().getServletContext().getRealPath(reporteJasper);
            OutputStream oS = null;
            //       oS = response.getOutputStream();
// Compilamos el .jrxml y lo cargamos : reporteJasper
            //     final String jasperName = JasperCompileManager.compileReportToFile(path);
            //     final JasperReport report = (JasperReport) JRLoader.loadObject(jasperName);
// Rellenamos el report pasándole al informe la lista de parámetros y el datasource 



            ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
// path Cede
            System.out.println(" 15 jasperTemplate : " + jasperTemplate);
//            JasperReport jasperReport1 = JasperCompileManager.compileReport(jasperTemplate);
            JasperReport report = JasperCompileManager.compileReport(extContext.getRealPath("/reports/Regist_Cargo.jasper"));
            System.out.println("   15a ");

//            final JasperPrint print = JasperFillManager.fillReport(jasperReport1, parameters, conn);
            final JasperPrint print = JasperFillManager.fillReport(report, parameters, conn);
// Exportamos el informe a HTML 
            System.out.println("   15b ");
            final JRHtmlExporter exporter = new JRHtmlExporter();
            System.out.println("   15c ");
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            System.out.println("   15d ");
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, oS);
            System.out.println("   15e ");
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "image?image=");
            System.out.println("   15f ");
            exporter.exportReport();
            System.out.println("   16 ");

            System.out.println(" image");
            //***
        } catch (Exception e) {
        }
    }

    public void generarReporte() throws JRException {
// DATASOURCE Y PARAMETERS AQUI
        try {
            System.out.println(" 1  generaReporte() ...");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            System.out.println(" 2 ");
            conn.setAutoCommit(false);
            System.out.println(" 3 ");
            String idCliente = expedient.getCodExp().toString();
            System.out.println(" 4 ");
            Map parameters = new HashMap();
            System.out.println(" 5 ");
            parameters.put("P_IdReg", idCliente);
            System.out.println(" 6");
//            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(getClass().getClassLoader().getResourceAsStream("reports/Regist_Cargo.jasper"));
//            JasperReport report = JasperCompileManager.compileReport(extContext.getRealPath("/reports/Regist_Cargo.jrxml"));
            String path = "/reports/Regist_Cargo.jrxml";
            System.out.println(" 7 ");
            JasperPrint print = JasperFillManager.fillReport(path, parameters, conn);
            System.out.println(" 8 ");
            byte[] bytes = JasperExportManager.exportReportToPdf(print);
            System.out.println(" 9 ");
            FacesContext context = FacesContext.getCurrentInstance();
            System.out.println(" 10 ");
            HttpServletResponse response = (HttpServletResponse) context
                    .getExternalContext().getResponse();
            System.out.println(" 11 ");
            response.addHeader("Content-disposition",
                    "attachment;filename=reporte.pdf");
            System.out.println(" 12 ");
            response.setContentLength(bytes.length);
            System.out.println(" 13 ");
            response.getOutputStream().write(bytes);
            System.out.println(" 14 ");
            response.setContentType("application/pdf");
//            context.responseComplete();
            System.out.println(" 15 ");
            context.responseComplete();
            System.out.println(" fin ");





        } catch (Exception e) {
        }


    }

    //   public StreamedContent getArchivoPDF(String path) throws JRException {
    public void archivoPDF() throws SQLException {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "emilima_tradoc";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "carloscd3";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, userName, password);
            System.out.println("Connected to the database EmiLima_TraDoc");
        } catch (Exception e) {
        }
        InputStream inputStream = null;
        // parameters.put("ALGUN_PARAMETRO", ID_PARAMETRO);
        String idCliente = expedient.getCodExp().toString();
        Map parameters = new HashMap();
        System.out.println(" 18 ");
        parameters.put("P_IdReg", idCliente);
        String path = "Regist_Cargo.jrxml";
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            System.out.println(" 12 ");
            conn.setAutoCommit(false);

            System.out.println(" ingrese de ArchivoPDF");
            ByteArrayOutputStream Teste = new ByteArrayOutputStream();
            System.out.println(" a1 ");
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(getClass().getClassLoader().getResourceAsStream("Regist_Cargo.jrxml"));
            System.out.println(" a2 ");
            JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, conn);
            System.out.println(" a3 ");
            JRExporter exporter = new net.sf.jasperreports.engine.export.JRPdfExporter();
            System.out.println(" a4 ");
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, Teste);
            System.out.println(" a5 ");
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            System.out.println(" a6 ");
            exporter.exportReport();
            System.out.println(" a7 ");
            inputStream = new ByteArrayInputStream(Teste.toByteArray());
            System.out.println(" sali de ArchivoPDF");
        } catch (JRException ex) {
        }
        //     return new DefaultStreamedContent(inputStream, "application/pdf", "nombre_archivo");

    }

    public void ultrepot() throws JRException {
        try {
            System.out.println("   ultrepot() ...");
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            System.out.println(" 12 ");
            conn.setAutoCommit(false);
            HttpServletResponse response = null;


            String path = "/reports/Regist_Cargo.jrxml";
            System.out.println(" 14 ");
            InputStream jasperTemplate = FacesContext.getCurrentInstance()
                    .getExternalContext().getResourceAsStream(path);
            // path
            System.out.println(" 15 jasperTemplate : " + jasperTemplate);
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperTemplate);
            System.out.println(" 16 ");
//            Map parameters = new HashMap();

            String idCliente = expedient.getCodExp().toString();
            System.out.println(" 17 ");
            Map parameters = new HashMap();
            System.out.println(" 18 ");
            parameters.put("P_IdReg", idCliente);
            System.out.println(" 2 ");


            //          JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);


//        JasperReport report = JasperCompileManager.compileReport(path);
            JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, conn);

            ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
            response = (HttpServletResponse) ectx.getResponse();
            OutputStream out = response.getOutputStream();



            byte[] bytes = JasperExportManager.exportReportToPdf(print);

            response.setHeader("Content-disposition", "attachment; filename=ListadoPDF");
            String tipo = "P";
            response.setContentType(tipo);
            //response.setHeader("Cache-Control", "private");
            //response.setHeader("Pragma", "");
            response.setContentLength(bytes.length);
            out.write(bytes);
            out.flush();
            out.close();


        } catch (Exception e) {
        }

    }

//*----------------------------------------------------------------------        
    public Expediente getCurrent() {
        return current;
    }

    public void setCurrent(Expediente current) {
        this.current = current;
    }

    public Inmuebles getInmueble() {
        return inmueble;
    }

    public void setInmueble(Inmuebles inmueble) {
        this.inmueble = inmueble;
    }

    public InteresArea getInterarea() {
        return interarea;
    }

    public void setInterarea(InteresArea interarea) {
        this.interarea = interarea;
    }

    public Interesado getInteresado() {
        return interesado;
    }

    public void setInteresado(Interesado interesado) {
        this.interesado = interesado;
    }

    public TipoDocTra getTipotradoc() {
        return tipotradoc;
    }

    public void setTipotradoc(TipoDocTra tipotradoc) {
        this.tipotradoc = tipotradoc;
    }

    public List<Expediente> getFilteredExped() {
        return filteredExped;
    }

    public void setFilteredExped(List<Expediente> filteredExped) {
        this.filteredExped = filteredExped;
    }
    /*
     public String getVarExpedNum() {
     String nexpe = " "; //"000";
     //        bloque = bloque.concat(String.valueOf(expedient.getCodExp()));
     //        nexpe= String.valueOf(expedient.getCodExp());
     nexpe = nexpe+expedient.getCodExp();
     //return bloque.substring(bloque.length() - 3);
     return nexpe;
     }

     public String getVarAsunto() {
     String asunto = ""; //"000";
     //        bloque = bloque.concat(String.valueOf(expedient.getCodExp()));
     //        asunto= String.valueOf(expedient.getAsunto());
     asunto = expedient.getAsunto();
     //return bloque.substring(bloque.length() - 3);
     return asunto;
     }

     public String getVarFolios() {
     String folios = "";
     folios = String.valueOf(expedient.getFolios());
     return folios;
     }

     public String getVarRemite() {
     String remite = "";
     remite = expedient.getRemitente();
     return remite;
     }

     public String getVarDetalle() {
     String detalle = "";
     detalle = expedient.getDetalleExpe();
     return detalle;
     }

     //    public TipoDocTra getVarTipDoc() {
     public String getVarTipDoc() {
     String tipDoc = "- ";
     //        tipDoc = expedient.getTipoDocTra().getNombre();
 
     //        TipoDocTra ttra = new TipoDocTra(tipDoc);
        
     tipDoc = tipDoc.concat(String.valueOf(expedient.getTipoDocTra()));
     //       System.out.println("------1--------- tipDoc : " + tipDoc);
     //        tipDoc = expedient.getTipoDocTra().getNombre();
     //       System.out.println("------2--------- tipDoc : " + tipDoc);
     //        tipDoc = String.valueOf(expedient.getTipoDocTra().getNombre());
     //     System.out.println("------3--------- tipDoc : " + tipDoc);
        
     //       String tipDoc = String.valueOf(expedient.getTipoDocTra().getNombre());
     //        String ytipDoc = String.valueOf(expedient.getTipoDocTra().toString());
     String ytipDoc = "ss";
     //   System.out.println("------4--------- tipDoc : " + ytipDoc);
        
        
        
     return tipDoc;
     }

     public String getVarTipTrami() {
     String tramite = "";
     //          tramite = String.valueOf(expedient.getTipoTramite().getNombre());
     //     tramite = expedient.getTipoTramite().getNombre();
     System.out.println(" ................ Tramite : " + tramite);
     tramite = "";
     return tramite;
     }

     public String getVarResponsa() {
     String responsa = "";
     //   responsa = expedient.getTrabajador().getNombres().trim();  // +" "+expedient.getTrabajador().getApePat().trim();
     //      responsa = String.valueOf(expedient.getTrabajador().getNombres().trim());
            
     System.out.println(" ----------------------- responsab : " + responsa);
     responsa = "ss";
     return responsa;
     }
     */

    public String getEstado() {
        return estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }

    public List<Expediente> getList_exped() {
        return list_exped;
    }

    public List<Expediente> getListaExpAllDia() {
        lista = new LinkedList<Expediente>();
        try {
//            lista = ejbFacade.findAll();  ok    Cede3
            int numl = 0;
            for (Expediente v : ejbFacade.findAll()) {
                SimpleDateFormat formateador = new SimpleDateFormat("yyyy-MM-dd");
                String ahora = formateador.format(v.getFechaReg());
                Date utilDate = new Date();
                long lnMilisegundos = utilDate.getTime();
                Date hoydia = new java.sql.Date(lnMilisegundos);
                Calendar hoy = Calendar.getInstance();
                int hdia = hoy.get(Calendar.DATE);
                int hmes = hoy.get(Calendar.MONTH) + 1;
                int hani = hoy.get(Calendar.YEAR);
                int vanio = Integer.parseInt(ahora.substring(0, 4));
                int vmes = Integer.parseInt(ahora.substring(5, 7));
                int vdia = Integer.parseInt(ahora.substring(8, 10));
//                if (vmes == 10) {
//                    String hoydia1 = hoydia.toString();
//                }
                if (hdia == vdia && hmes == vmes && hani == vanio) {  // && v.getEstado().getIdEstado().equals("01")
                    lista.add(v);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lista;

    }

    public List<Expediente> getListaExpAll() {
        lista = new LinkedList<Expediente>();
        try {
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
            EntityManager em = factory.createEntityManager();
            TypedQuery<Expediente> queryAll = em.createNamedQuery("Expediente.findAllFecha", Expediente.class);
            lista = queryAll.getResultList();
            // lista = ejbFacade.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lista;
    }

    public List<Expediente> getListaExpAlloriginal() {
        lista = new LinkedList<Expediente>();
        try {
            lista = ejbFacade.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lista;

    }

    public void Filtrar_lista_Fecha() {   // Filtra los Expedientes del Dia 
        lista = new LinkedList<Expediente>();
        for (Expediente v : ejbFacade.findAll()) {
            if (v.getFechaReg().equals(fecha_emision) && v.getEstado().getIdEstado().equals("01")) {
//            if (v.getFechaReg().equals(fecha_emision)) {
                lista.add(v);
            }
        }
    }

    public void Segui_Fechas_priori() {   // Filtra Registros del Rango de Fecha a seguir
    }

    public List<Expediente> getLista() {
        return lista;
    }

    public Expediente getExpedient() {
        return expedient;
    }

    public void setExpedient(Expediente expedient) {
        this.expedient = expedient;
    }

//********************************************************************    
    public Date getFecha_emision() {
        return fecha_emision;
    }

    public void setFecha_emision(Date fecha_emision) {
        this.fecha_emision = fecha_emision;
    }

    public Date getFecha_ini() {
        return fecha_ini;
    }

    public void setFecha_ini(Date fecha_ini) {
        this.fecha_ini = fecha_ini;
    }

    public Date getFecha_fin() {
        return fecha_fin;
    }

    public void setFecha_fin(Date fecha_fin) {
        this.fecha_fin = fecha_fin;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Expediente) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Expediente();
        selectedItemIndex = -1;
        System.out.println("----------- Stoy en create Exped");
        return "Create";
    }

    public void prepareCreatecd() {
        expedient = new Expediente();
        current = new Expediente();
        System.out.println("----------- Stoy en PrepareCreatecd Exped");

    }

    public void prepararInsertar(ActionEvent actionEvent) {
        expedient = new Expediente();
    }

    /*    public String insertaExp() {
     System.out.println("----------- IsnertaExp Expediente");
     try {
     ejbFacade.create(expedient);
     //            getFacade().create(current);
     JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpedienteCreated"));
     return prepareCreate();
     } catch (Exception e) {
     JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
     return null;
     }
     } 
     */
    public String create() {
        System.out.println("----------- Creando Expediente");
        try {

//            current.setEstado("01");

            getFacade().create(current);
//            getFacade().create(expedient);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpedienteCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Expediente) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        System.out.println("----------- Stoy en preparedEdit ");
        return "Edit";
    }

    public String update() {
        try {
            current = expedient; // agreg
            getFacade().edit(current);
//            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpedienteUpdated"));
//            FacesContext context = FacesContext.getCurrentInstance();
//            context.addMessage(null, new FacesMessage(" Registro Modificado exitosamente", "._."));
                    
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Moficiación Procesada ..!", "Registro Modificado Correctamente");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
           
//            return "View";
//            return null;
        } catch (Exception e) {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(" Error en Modificacion ", "-_-"));
//            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));

        }
        current = null;
        expedient = null;
        prepareCreatecd();
        return null;
    }
//------------------------------------------------------------------------
 /*     public void prepararActualizar(Integer id){
     IntegranteDao integranteDao = new IntegranteDaoImpl();
     integrante = integranteDao.buscarPorId(id);
     }
     */

    public void prepEdit() {
        current = (Expediente) getItems().getRowData();
        System.out.println("----------- Stoy en Tengo el EDIT Exped");
    }

    public String eliminaExp() {
        try {
//             almProductoFacade.remove(producto);
            System.out.println(" ----------- Expe Eliminado ");
            ejbFacade.remove(expedient);
            //         FacesContext context = FacesContext.getCurrentInstance();
            //          context.addMessage(null, new FacesMessage(" Registro Eliminado exitosamente", "._."));
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Eliminación Procesada ..!", "Registro Eliminado Correctamente");
            RequestContext.getCurrentInstance().showMessageInDialog(message);

        } catch (Exception e) {
            e.printStackTrace();
        }

        //  return "requerimientos";
        return null;
    }

    public String editaExpedi() {
        System.out.println(" ----------- String editaExpedi() ...................... ");
        try {
//            ejbFacade.remove(expedient);
            ejbFacade.edit(expedient);
            //    FacesContext context = FacesContext.getCurrentInstance();
            //    context.addMessage(null, new FacesMessage("editaExpedi() Expediente Actualizado exitosamente", "-_-"));
            System.out.println(" ----------- con Exito ...................... ");
//            getFacade().edit(current);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(" ----------- Exception " + e);
        }
        //  return "requerimientos";
        return null;
    }

    public String grabaExpedi() throws JRException, IOException {
        //  System.out.println(" ----------- String grabaExpedi() ...................... ");
        int grabo = 0;
        String codgen1 = "";
        String codgen2 = "";
        String codgen3 = "";
        String codgen4 = "";
        UsuarioController usuarioController = (UsuarioController) JsfUtil.getManagedBean("usuarioController");
        int idusu = usuarioController.getUsuario().getIdUsuario();
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("cede3-warPU", System.getProperties());
        EntityManager em = factory.createEntityManager();
        Query q = em.createQuery("SELECT t FROM Trabajador t join t.usuario u  WHERE u.idUsuario = :codtra "); // jalar id de otra tabla
//        Query q = em.createQuery("SELECT t FROM Trabajador t WHERE t.idUsuario = :codtra ");        
        q.setParameter("codtra", idusu);
        Trabajador trabajador;
        String page = null;
        try {
            trabajador = (Trabajador) q.getSingleResult();
            this.trabajador = trabajador;   // alamacena data del Trabajador en consulta
            Estado est = new Estado();
            est.setIdEstado("01");
            expedient.setEstado(est);
            Trabajador traba = new Trabajador();
            traba.setIdResponsable(this.getTrabajador().getIdResponsable());
            expedient.setTrabajador(traba);
            expedient.setFkCodificador(1);
            // http://carloszuluaga.wikidot.com/articulos:manejo-de-fechas-en-java-i    
            Date utilDate = new java.util.Date();
            long lnMilisegundos = utilDate.getTime();
            Timestamp fechahora = new java.sql.Timestamp(lnMilisegundos);
            expedient.setFechaReg(fechahora);
//            String codgenerado = expedient.tipoTramite.sigla+expedient.interesArea.interesAreaPK.idInter+expedient.interesArea.interesAreaPK.idIntArea+expedient.interesArea.correla;
            codgen1 = expedient.getTipoTramite().getSigla().toString();
            codgen2 = expedient.getInteresArea().getInteresAreaPK().getIdInter().toString();
            codgen3 = expedient.getInteresArea().getInteresAreaPK().getIdIntArea().toString();
            codgen4 = expedient.getInteresArea().getCorrela().toString();
            expedient.setCodExp(codgen1 + codgen2 + codgen3 + codgen4);
            /*            
             System.out.println("Exp  " + expedient.getCodExp());
             System.out.println("Fecha" + expedient.getFechaReg());
             System.out.println("NumExpIngres   " + expedient.getNumexpeIngr());
             System.out.println("Asunto         " + expedient.getAsunto());
             System.out.println("Folios         " + expedient.getFolios());
             System.out.println("Remitente      " + expedient.getRemitente());
             System.out.println("Detall Exp     " + expedient.getDetalleExpe());
             System.out.println("Tip Doc Tramit " + expedient.getTipoDocTra());
             System.out.println("Tip Trabajador " + expedient.getTrabajador().getIdResponsable());
             System.out.println("Codificador    " + expedient.getFkCodificador());
             System.out.println("Tip Tramit     " + expedient.getTipoTramite());
             System.out.println("Tip Inmueble   " + expedient.getInmuebles());
             System.out.println("Tipo de Estado " + expedient.getEstado());
             System.out.println("Observac       " + expedient.getObservac());
             System.out.println("Tip Prioridad  " + expedient.getTipoPriorida());
             System.out.println("Proveido       " + expedient.getProveido());
             System.out.println("Interesado     " + expedient.getInteresArea().getInteresAreaPK().getIdInter());
             System.out.println("AreaInteres    " + expedient.getInteresArea().getInteresAreaPK().getIdIntArea());
             */
            ejbFacade.create(expedient);

//                FacesContext context = FacesContext.getCurrentInstance();
//                context.addMessage(null, new FacesMessage("editaExpedi() Expediente Actualizado exitosamente", "-_-"));
            grabo = 1;
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(" Registro Grabado exitosamente", "._."));
            System.out.println(" -----  grabo = 1");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(" ----------- grabaRegistro Exception " + e);
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage(null, new FacesMessage(" Error Al grabar Registro ", "._."));
        }
        if (grabo == 1) {
            String codgene = codgen1 + codgen2 + codgen3 + codgen4;         //System.out.println(" .... Codigo generado " + codgene);
            impCargo(codgene);
            int newcod1 = Integer.parseInt(codgen4) + 1;
            String newcod2 = String.format("%06d", newcod1);/* %=primer parametro, en este caso sera numero; 0=relleño; 5=longitud para el resultado; d=indica que numero es un numero decimal */
//-------------------- Actualizo Nº Correlativo del Area Interesada
            try {
                InteresAreaPK iapk = new InteresAreaPK();
                iapk.setIdInter(codgen2);
                iapk.setIdIntArea(codgen3);
                //setIdIntArea(codgen2+codgen3);
                InteresArea iarea = new InteresArea();
                iarea.setInteresAreaPK(iapk);
// Modificacion de AreaInteresada                
                // current.getInteresAreaPK().setIdInter(current.getInteresado().getIdInter());
                // getFacade().edit(current);
                InteresAreaPK iapk11 = new InteresAreaPK();
                InteresArea yo = getEjbAint().find(iapk);
                yo.setCorrela(newcod2);
                getEjbAint().edit(yo);
                //getEjbAint().edit(iarea);
            } catch (Exception e) {
                System.out.println(" --------- Errror al Grabar Num Correlativo : " + e);
            }
//-----------------------------------------------------------------                  
        }
        System.out.println("saliendo de grabar .................... ");
        return null;
    }

//    public void initCargo() throws JRException {
    public void initCargo(String codigo) throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = codigo; //expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/Regist_Cargo.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
            System.out.println(" iniCargo Saliendo");
        } catch (Exception e) {
            System.out.println(" e initCargo : " + e);
        }
    }

//    public void impCargo() throws JRException, IOException {
    public void impCargo(String codigo) throws JRException, IOException {
//        initCargo();
        initCargo(codigo);
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "Reg_Cargo";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
        System.out.println(" impCargo Saliendo");
    }

    public String destroy() {
        current = (Expediente) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ExpedienteDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public Expediente getExpediente(java.lang.String id) {
        return ejbFacade.find(id);
    }

    @FacesConverter(forClass = Expediente.class)
    public static class ExpedienteControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ExpedienteController controller = (ExpedienteController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "expedienteController");
            return controller.getExpediente(getKey(value));
        }

        java.lang.String getKey(String value) {
            java.lang.String key;
            key = value;
            return key;
        }

        String getStringKey(java.lang.String value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Expediente) {
                Expediente o = (Expediente) object;
                return getStringKey(o.getCodExp());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Expediente.class.getName());
            }
        }
    }
}
